package com.ruoyi.verify.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonView;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.easyExcel.EasyExcelListenerFactory;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.verify.domain.VerifyMemberFactoryType;
import com.ruoyi.verify.domain.VerifyMemberInfo;
import com.ruoyi.verify.service.IVerifyMemberInfoService;
import com.ruoyi.verify.transform.FactoryInfo;
import com.ruoyi.verify.transform.VerifyTeamInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("memberinfo")
@Slf4j
public class VerifyMemberInfoController extends BaseController
{

    @Autowired
    private IVerifyMemberInfoService verifyMemberInfoService;

    /**
     * 查询${tableComment}
     */
    @GetMapping("get/{memberid}")
    public VerifyMemberInfo get(@PathVariable("memberid") Long memberid)
    {
        return verifyMemberInfoService.selectVerifyMemberInfoById(memberid);

    }

//    /**
//     * yuanchengdiaoyong
//     */
//    @PostMapping("getmemberinfo")
//    public List<VerifyMemberInfo> getmemberinf(@RequestBody Map<String,String> memberinfo)
//    {
//        String membername = memberinfo.get("membername");
//        String jobnumber = memberinfo.get("jobnumber");
//
//        return verifyMemberInfoService.selectVerifyMemberInfoById(memberid);
//
//    }



    /**
     * 查询【请填写功能名称】列表
     */
    @GetMapping("list")
    public R list(VerifyMemberInfo verifyMemberInfo)
    {
        startPage();
        return result(verifyMemberInfoService.selectVerifyMemberInfoList(verifyMemberInfo));
    }

    /**
     * 从审核组中查询人员列表
     * 前台在查询时额外传父计划所属factorycode和verifytype 2020/11/29修改 需要多传入year（上表中填写的审核日期）
     * 2020/10/28 22:29
     */
    @GetMapping("verifyteamlist")
    public R verifyteamlist(VerifyMemberInfo verifyMemberInfo)
    {
        if(verifyMemberInfo.getCurrentTime()==null || verifyMemberInfo.getCurrentTime().equals("")){
            return R.error("请填写审核时间！");
        }
        startPage();
        return result(verifyMemberInfoService.selectVerifyMemberTeamList(verifyMemberInfo));
    }


    /**
     * 新增保存【请填写功能名称】
     */
    @PostMapping("save")
    public R addSave(@RequestBody VerifyMemberInfo verifyMemberInfo)
    {
        return toAjax(verifyMemberInfoService.insertVerifyMemberInfo(verifyMemberInfo));
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @PostMapping("update")
    public R editSave(@RequestBody VerifyMemberInfo verifyMemberInfo)
    {
        return toAjax(verifyMemberInfoService.updateVerifyMemberInfo(verifyMemberInfo));
    }

    /**
     * 删除${tableComment}
     */
    @PostMapping("remove")
    public R remove(@RequestBody  VerifyMemberInfo verifyMemberInfo)
    {
        return toAjax(verifyMemberInfoService.deleteVerifyMemberInfoByIds(verifyMemberInfo));
    }

//    /**
//     * 新增专家组
//     */
//    @PostMapping("creatememberteam")
//    @Transactional(rollbackFor = Exception.class)
//    public R createMemberTeam(@RequestBody VerifyMemberFactoryType verifyMemberFactoryType)
//    {
//        for(Long mid:verifyMemberFactoryType.getMemberidlist()){
//
//
//            verifyMemberInfoService.insertVerifyFactoryType(verifyMemberFactoryType.getVerifytype(),verifyMemberFactoryType.getFactorycode(),mid);
//        }
//        return  R.ok();
//
//    }

    /**
     * 新增专家组
     * @param verifyMemberFactoryType
     * @return
     */
    @PostMapping("addteammember")
    @Transactional(rollbackFor = Exception.class)
    public R createMemberTeam(@RequestBody VerifyMemberFactoryType verifyMemberFactoryType)
    {
        int count = 0;
        StringBuilder timeMsg = null;
        StringBuilder codeMsg = null;
        StringBuilder stringBuilder = new StringBuilder();
        String[] factorycodes = verifyMemberFactoryType.getFactorycodes();
        String[] factorynames = verifyMemberFactoryType.getFactorynames();
        if(factorycodes==null || factorynames==null || factorycodes.length!=factorynames.length){
            log.error("传入的工厂code和工厂name数组不一致");
            return R.error(505,"传入的工厂code和工厂name数组不一致");
        }
//        String memberid = ServletUtils.getRequest().getHeader(Constants.CURRENT_ID);
//            if(verifyMemberInfoService.ifHaveYearInSrm(verifyMemberFactoryType.getVerifytype(),factorycode,verifyMemberFactoryType.getYear())){
//                return R.error(505,"此审核类型下的版本号已存在");
//            }
//
//        //判断新增的专家组是否和之前的专家组时间范围冲突
//        if(verifyMemberInfoService.ifTimeConflict(verifyMemberFactoryType.getVerifytype(), verifyMemberFactoryType.getFactorycode(), verifyMemberFactoryType.getStarttime())){
//            return R.error(505, "时间范围有误，此年份专家组的开始时间包含于前年份专家组，请修改此年份专家组的开始时间，或前年份专家组的结束时间。");
//        }
//        for(String fcode : verifyMemberFactoryType.getFactorycodes()){
//            if(verifyMemberInfoService.ifHaveYearInSrm(verifyMemberFactoryType.getVerifytype(),fcode,verifyMemberFactoryType.getYear())){
//
//                return R.error(505,"此审核类型下的版本号已存在");
//            }
//            //判断新增的专家组是否和之前的专家组时间范围冲突
//            if(verifyMemberInfoService.ifTimeConflict(verifyMemberFactoryType.getVerifytype(), fcode, verifyMemberFactoryType.getStarttime(),verifyMemberFactoryType.getEndtime())){
//                return R.error(505, "当前版本专家组与已生效专家组时间范围冲突，请修改时间范围。");
//            }
//        }

        for(int i=0;i<factorycodes.length;i++){
            if(verifyMemberInfoService.ifHaveYearInSrm(verifyMemberFactoryType.getVerifytype(),factorycodes[i],verifyMemberFactoryType.getYear())){
                if(codeMsg==null){
                    codeMsg=new StringBuilder("当前审核类型与以下工厂版本冲突：\r\n");
                }
                codeMsg.append((factorynames[i]+" \r\n"));
            }
            //判断新增的专家组是否和之前的专家组时间范围冲突
            if(verifyMemberInfoService.ifTimeConflict(verifyMemberFactoryType.getVerifytype(), factorycodes[i], verifyMemberFactoryType.getStarttime(),verifyMemberFactoryType.getEndtime())){
                if(timeMsg==null){
                    timeMsg=new StringBuilder("当前审核类型与以下工厂时间范围冲突：\r\n");
                }
                timeMsg.append((factorynames[i]+" \r\n"));
            }
        }
        if(timeMsg!=null){
            stringBuilder.append(timeMsg);
        }
        if(codeMsg!=null){
            stringBuilder.append(codeMsg);
        }
        if(!stringBuilder.toString().equals("")){
            log.error(stringBuilder.toString());
            return R.error(505, stringBuilder.toString());
        }

        for(String fcode : verifyMemberFactoryType.getFactorycodes()) {
//
//            VerifyMemberInfo verifyMemberInfo1 = new VerifyMemberInfo();
//            verifyMemberInfo1.setFactorycode(fcode);
//            verifyMemberInfo1.setVerifytype(verifyMemberFactoryType.getVerifytype());
//            verifyMemberInfo1.setYear(verifyMemberFactoryType.getYear());
//            List<VerifyMemberInfo> verifyMemberInfos = verifyMemberInfoService.selectVerifyTeamMemberInfoList(verifyMemberInfo1);
//            if (verifyMemberInfos.size() > 0) {
//                List<String> factorynamelist = verifyMemberInfos.stream().map(v -> v.getFactoryname()).collect(Collectors.toList());
//                String factorynames = String.join(" ", factorynamelist);
//                return R.error(505, factorynames+"下 "+verifyMemberInfos.get(0).getVerifytype()+"已存在，不可以新增已存在的专家组，若想修改成员，请在原专家组上修改，或删除原专家组后再新增。");
//            }

            for (Long mid : verifyMemberFactoryType.getMemberids()) {
                VerifyMemberInfo verifyMemberInfo = new VerifyMemberInfo();
                verifyMemberInfo.setStarttime(verifyMemberFactoryType.getStarttime());
                verifyMemberInfo.setEndtime(verifyMemberFactoryType.getEndtime());
                verifyMemberInfo.setYear(verifyMemberFactoryType.getYear());
                verifyMemberInfo.setMemberid(mid);
                verifyMemberInfo.setFactorycode(fcode);
                verifyMemberInfo.setVerifytype(verifyMemberFactoryType.getVerifytype());
//                verifyMemberInfo.setMemberid(Long.parseLong(memberid));
                verifyMemberInfo.setStatus(verifyMemberFactoryType.getStatus());
                verifyMemberInfoService.insertVerifyTeamMember(verifyMemberInfo);
            }
        }
        return  R.ok();

    }

//    /**
//     * 判断版本号是否重复
//     * @return
//     */
//    @GetMapping("ifRepeatYear")
//    public R ifRepeatYear(String year)
//    {
//        return R.ok().put("ifRepeatYear",verifyMemberInfoService.ifHaveYearInSrm(year));
//    }


//    /**
//     * 点击专家组进入编辑人员列表
//     */
//    @GetMapping("getmember/{verifytype}/{factorycode}")
//    public R getmember(@PathVariable("verifytype") String verifytype, @PathVariable("factorycode") String factorycode)
//    {
//
//        List<VerifyMemberInfo> verifyMemberInfos = verifyMemberInfoService.selectVerifyMemberInfoByVerifytypeFactorycode(verifytype, factorycode);
//        VerifyTeamInfo verifyTeamInfo = new VerifyTeamInfo();
//        List<Long> memberids = verifyMemberInfos.stream().map(vmi -> vmi.getMemberid()).collect(Collectors.toList());
//        List<String> membernames = verifyMemberInfos.stream().map(vmi -> vmi.getMembername()).collect(Collectors.toList());
//        verifyTeamInfo.setMemberids(memberids);
//        verifyTeamInfo.setMembernames(membernames);
//        verifyTeamInfo.setFactorycode(factorycode);
//        verifyTeamInfo.setFactoryname(verifyMemberInfos.get(0).getFactoryname());
//
//        List<VerifyTeamInfo> verifyTeamInfos = new ArrayList<>();
//        verifyTeamInfos.add(verifyTeamInfo);
//
//        return jacResult(verifyTeamInfos);
//    }

    /**
     * 点击专家组进入编辑人员列表
     */
    @GetMapping("getmember/{verifytype}/{factorycode}/{year}")
    public R getmember(@PathVariable("verifytype") String verifytype, @PathVariable("factorycode") String factorycode,@PathVariable("year") String year)
    {

        List<VerifyMemberInfo> verifyMemberInfos = verifyMemberInfoService.selectVerifyMemberInfoByVerifytypeFactorycodeAndYear(verifytype, factorycode,year);
        VerifyTeamInfo verifyTeamInfo = new VerifyTeamInfo();
        List<Long> memberids = verifyMemberInfos.stream().map(vmi -> vmi.getMemberid()).collect(Collectors.toList());
        List<String> membernames = verifyMemberInfos.stream().map(vmi -> vmi.getMembername()).collect(Collectors.toList());
        verifyTeamInfo.setMemberids(memberids);
        verifyTeamInfo.setMembernames(membernames);

        Map<String,List<Long>> map = new HashMap<>();
        verifyMemberInfos.forEach(vmi ->{//统计各个事业部下人员数
            if(!map.containsKey(vmi.getGs())){
                List<Long> newMemberidList = new ArrayList<>();
                newMemberidList.add(vmi.getMemberid());
                map.put(vmi.getGs(),newMemberidList);
            }else{
                List<Long> memberidList = map.get(vmi.getGs());
                memberidList.add(vmi.getMemberid());
                map.put(vmi.getGs(),memberidList);
            }
        });


        verifyTeamInfo.setVerifytype(verifytype);
        verifyTeamInfo.setFactorycode(factorycode);
        verifyTeamInfo.setFactoryname(verifyMemberInfos.get(0).getFactoryname());
        verifyTeamInfo.setStarttime(verifyMemberInfos.get(0).getStarttime());
        verifyTeamInfo.setEndtime(verifyMemberInfos.get(0).getEndtime());
        verifyTeamInfo.setYear(verifyMemberInfos.get(0).getYear());
        verifyTeamInfo.setStatus(verifyMemberInfos.get(0).getStatus());

        List<Object> verifyTeamInfos = new ArrayList<>();

        Set<Map.Entry<String, List<Long>>> entries = map.entrySet();


        List<Map<String, Object>> collect = entries.stream().map(e -> {
            Map<String, Object> newMap = new HashMap<>();
            newMap.put("gs", e.getKey());
            newMap.put("memberNumbers", e.getValue().size());
            newMap.put("memberIds",e.getValue());
            return newMap;
        }).collect(Collectors.toList());


        verifyTeamInfos.add(verifyTeamInfo);
        verifyTeamInfos.add(collect);

        return jacResult(verifyTeamInfos);
    }

    /**
     * 专家组成员里点击事业部获取该事业部下的所有成员
     *  需要传year verifytype factorycode gs
     *  bm可选
     */
    @PostMapping("getmemberbygs")
    public R getmemberbygs(@RequestBody FactoryInfo factoryInfo){
        Integer pageNum = factoryInfo.getPageNum();
        Integer pageSize = factoryInfo.getPageSize();
        String sortField = factoryInfo.getSortField();
        String sortOrder = factoryInfo.getSortOrder();
        startPage(pageNum,pageSize,sortField,sortOrder);
        List<String> memberIds = factoryInfo.getMemberIds().stream().filter(m -> StringUtils.isNotEmpty(m)).collect(Collectors.toList());
        factoryInfo.setMemberId(StringUtils.join(memberIds, ","));
        return result(verifyMemberInfoService.selectVerifyMemberInfoByMemberids(factoryInfo));
    }


    /**
     * 根据传来的人员选择数返回基地人数统计分类
     */
    @PostMapping("getFactoryMemberCategory")
    public R getFactoryMemberCategory(@RequestBody FactoryInfo factoryInfo){
        List<String> memberIds = factoryInfo.getMemberIds().stream().filter(m -> StringUtils.isNotEmpty(m)).collect(Collectors.toList());
        factoryInfo.setMemberId(StringUtils.join(memberIds, ","));
        if(factoryInfo.getMemberIds()==null || factoryInfo.getMemberIds().size()==0){
            log.error("传来空的人员id数组");
            R.error("传来空的人员id数组");
        }

        List<VerifyMemberInfo> verifyMemberInfos = verifyMemberInfoService.selectVerifyMemberInfoByMemberids(factoryInfo);
        Map<String,List<Long>> map = new HashMap<>();
        verifyMemberInfos.forEach(vmi ->{//统计各个事业部下人员数
            if(!map.containsKey(vmi.getGs())){
                List<Long> newMemberidList = new ArrayList<>();
                newMemberidList.add(vmi.getMemberid());
                map.put(vmi.getGs(),newMemberidList);
            }else{
                List<Long> memberidList = map.get(vmi.getGs());
                memberidList.add(vmi.getMemberid());
                map.put(vmi.getGs(),memberidList);
            }
        });
        Set<Map.Entry<String, List<Long>>> entries = map.entrySet();


        List<Map<String, Object>> collect = entries.stream().map(e -> {
            Map<String, Object> newMap = new HashMap<>();
            newMap.put("gs", e.getKey());
            newMap.put("memberNumbers", e.getValue().size());
            newMap.put("memberIds",e.getValue());
            return newMap;
        }).collect(Collectors.toList());
        return jacResult(collect);
    }

    /**
     * 一键将所有专家库成员添加到专家组
     */
    @GetMapping("addAllVerifyMember")
    public R addAllVerifyMember(){
        VerifyMemberInfo verifyMemberInfo = new VerifyMemberInfo();
        verifyMemberInfo.setIfexpert("1");
        List<String> memberIds = verifyMemberInfoService.selectAllVerifyMemberid(verifyMemberInfo);
        Map<String,Object> map = new HashMap<>();
        map.put("memberIds",memberIds);
        return resultObject(map);
    }

    /**
     * 下载专家组导入模板
     */
    @GetMapping("/verifyTeamImportTemplate")
    public void verifyTeamImportTemplate(HttpServletResponse response, HttpServletRequest request)
    {
        try {
            response.setHeader("code", "0");
            String filename = "专家组人员导入模板.xlsx";
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, filename));
            ExcelUtil<VerifyTeamInfo> util = new ExcelUtil<>(VerifyTeamInfo.class);
            util.importTemplateExcel("用户",response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
            response.setHeader("code", "500");
        }
    }

    /**
     * 上传excel批量导入专家组
     */
    @PostMapping("verifyTeamImp")
    public R verifyTeamImp(MultipartFile file) throws IOException {
        List<VerifyTeamInfo> list = new ArrayList<>();//此list用来存储导入文件中的每行数据
        EasyExcelListenerFactory<VerifyTeamInfo> tf = new EasyExcelListenerFactory<>(list);
        AnalysisEventListener listener = tf.getListener();
        EasyExcel.read(file.getInputStream(),VerifyTeamInfo.class,listener).sheet().doRead();//执行完此句后list内就存了文件中数据
        List<String> jobnumberlist = list.stream().map(t -> t.getJobnumber()).collect(Collectors.toList());
        String jobnumbers = StringUtils.join(jobnumberlist, ",");
        VerifyMemberInfo verifyMemberInfo = new VerifyMemberInfo();
        verifyMemberInfo.setJobnumber(jobnumbers);
        if(jobnumberlist==null || jobnumberlist.size()==0){
            log.error("excel工号无效或系统中不存在这些人员");
            return R.error("excel工号无效或系统中不存在这些人员");
        }
        List<String> memberIds = verifyMemberInfoService.selectAllVerifyMemberid(verifyMemberInfo);
        Map<String,Object> map = new HashMap<>();
        map.put("memberIds",memberIds);
        return resultObject(map);
    }
//    /**
//     * 点击专家组进入编辑人员列表
//     */
//    @GetMapping("getmember/{id}")
//    public R getteaminfo(@PathVariable("id") Long verifyteamid)
//    {
//
//        List<VerifyMemberInfo> verifyMemberInfos = verifyMemberInfoService.selectVerifyMemberInfoByVerifytypeFactorycode(verifytype, factorycode);
//        VerifyTeamInfo verifyTeamInfo = new VerifyTeamInfo();
//        List<Long> memberids = verifyMemberInfos.stream().map(vmi -> vmi.getMemberid()).collect(Collectors.toList());
//        List<String> membernames = verifyMemberInfos.stream().map(vmi -> vmi.getMembername()).collect(Collectors.toList());
//        verifyTeamInfo.setMemberids(memberids);
//        verifyTeamInfo.setMembernames(membernames);
//        verifyTeamInfo.setFactorycode(factorycode);
//        verifyTeamInfo.setFactoryname(verifyMemberInfos.get(0).getFactoryname());
//
//        List<VerifyTeamInfo> verifyTeamInfos = new ArrayList<>();
//        verifyTeamInfos.add(verifyTeamInfo);
//
//        return jacResult(verifyTeamInfos);
//    }

    /**
     * 查询专家组列表
     */
    @GetMapping("teamlist")
    @JsonView(value = VerifyMemberInfo.teamMember.class)
    public R teamlist(VerifyMemberInfo verifyMemberInfo)
    {
        startPage();
        return result(verifyMemberInfoService.selectVerifyTeamMemberInfoList(verifyMemberInfo));
    }

    /**
     * 修改专家组内成员
     * @param verifyMemberFactoryType
     * @return
     */
    @PostMapping("editteammember")
    @Transactional(rollbackFor = Exception.class)
    public R editMemberTeam(@RequestBody VerifyMemberFactoryType verifyMemberFactoryType)
    {


//        for(String fcode : verifyMemberFactoryType.getFactorycodes()){
//            if(!verifyMemberFactoryType.getYear().equals(verifyMemberFactoryType.getOldyear()) && verifyMemberInfoService.ifHaveYearInSrm(verifyMemberFactoryType.getVerifytype(),fcode,verifyMemberFactoryType.getYear())){
//                return R.error(505,"所选审核类型下有重复的版本号！");
//            }
//        }
        if(verifyMemberFactoryType.getYear().equals(verifyMemberFactoryType.getOldyear())){ //如果相等则表示修改专家组，先删除原先的专家组
            for(String fcode : verifyMemberFactoryType.getFactorycodes()){
                verifyMemberInfoService.deleteVerifyTeamMemberInfoByVerifytypeFactorycode(verifyMemberFactoryType.getVerifytype(),fcode,verifyMemberFactoryType.getYear());
            }
        }
        if(verifyMemberFactoryType.getMemberids()==null || verifyMemberFactoryType.getMemberids().equals("")){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(505,"请选择成员！");
        }

        return  createMemberTeam(verifyMemberFactoryType);

    }

    /**
     * 修改专家组生效状态
     * 需要接收verifytype factorycode year status  2020/11/29增加传入字段starttime endtime
     * status=0表示失效，1表示生效
     * 生效时需要判断生效时间范围是否和存在的专家组冲突
     */
    @PostMapping("editteamstatus")
    @Transactional(rollbackFor = Exception.class)
    public R editteamstatus(@RequestBody VerifyMemberInfo verifyMemberInfo)
    {
        //生效时判断时间范围是否冲突
        if(verifyMemberInfo.getStatus().equals("2") && verifyMemberInfoService.ifTimeConflict(verifyMemberInfo.getVerifytype(),verifyMemberInfo.getFactorycode(),verifyMemberInfo.getStarttime(),verifyMemberInfo.getEndtime())){
            return R.error(505,"当前版本专家组与已生效专家组时间范围冲突，请修改时间范围。");
        }
        verifyMemberInfoService.updateVerifyTeamStatus(verifyMemberInfo);
        return  R.ok();
    }

    /**
     * 导入专家库
     */
    @PostMapping("/imp")
    @ResponseBody
    public R imp(MultipartFile file) throws IOException {
        List<VerifyMemberInfo> list = new ArrayList<>();//此list用来存储导入文件中的每行数据
        EasyExcelListenerFactory<VerifyMemberInfo> tf = new EasyExcelListenerFactory<>(list);
        AnalysisEventListener listener = tf.getListener();
        EasyExcel.read(file.getInputStream(),VerifyMemberInfo.class,listener).sheet().doRead();//执行完此句后list内就存了文件中数据
        StringBuilder stringBuilder = new StringBuilder();
        int count = 0;
        for (VerifyMemberInfo t:list){
            //导入专家库需srm内存在此用户。首先判断用户是否已存在，存在则导入数据，不存在则跳过。
            if(verifyMemberInfoService.ifHaveMemberInSrm(t.getJobnumber())){
                //导入数据时，先删除再导入，相同工号数据会被覆盖
                verifyMemberInfoService.deleteVerifyTeamMemberInfo(t.getJobnumber());
                verifyMemberInfoService.updateVerifyMemberRole(t.getJobnumber(),"43");
                verifyMemberInfoService.importVerifyTeamMemberInfo(t);//实际导入过程，可以根据自身情况进行相应导入成功失败判断，并返回给前台
            }else {
                count++;
                stringBuilder.append(t.getJobnumber()+" "+t.getMembername()+";");
            }
        }
        if(count>0){
            stringBuilder.insert(0,"因SRM中不存在这些用户，以下"+count+"个人员导入失败：\r\n");
            stringBuilder.append("------------请联系管理员先开通这些用户");
            return R.error(505,stringBuilder.toString());
        }
        return R.ok();
    }

    @GetMapping("/exp")
    @ResponseBody
    public void exp(VerifyMemberInfo verifyMemberInfo,HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("code", "0");
        List<VerifyMemberInfo> list = verifyMemberInfoService.selectVerifyMemberInfoList(verifyMemberInfo); //被导出数据本身，这里的list只是测试，具体业务可能要进行筛选
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
//        response.setHeader("Content-disposition", "attachment;filename=test.xlsx");
        String filename = "专家库成员导出文件.xlsx";
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, filename));
        ExcelUtil<VerifyMemberInfo> util = new ExcelUtil<>(VerifyMemberInfo.class);
        EasyExcel.write(response.getOutputStream(), VerifyMemberInfo.class).sheet("专家库人员").doWrite(list);//‘模板1’可根据业务内容自行变更

    }

    @GetMapping("/importTemplate")
    @ResponseBody
    @ApiOperation(value = "get importtemple",notes = "test")
    public void importTemplate(HttpServletResponse response, HttpServletRequest request)
    {
        try {
            response.setHeader("code", "0");
            String filename = "专家库人员导入模板.xlsx";
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, filename));
            ExcelUtil<VerifyMemberInfo> util = new ExcelUtil<>(VerifyMemberInfo.class);
            util.importTemplateExcel("用户",response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
            response.setHeader("code", "500");
        }
    }

    /**
     * 删除专家库成员
     */
    @GetMapping("removeTeamMemberInfo")
    @Transactional(rollbackFor = Exception.class)
    public R deleteVerifyTeamMemberInfo(String jobnumbers)
    {
        String[] split = jobnumbers.split(",");
        for (String s : split) {
            verifyMemberInfoService.deleteVerifyTeamMemberInfo(s);
        }

        return R.ok();
    }

    /**
     * 手动导入某个成员到专家库
     */
    @PostMapping("/addExpertLibrary")
    @ResponseBody
    public R addExpertLibrary(@RequestBody VerifyMemberInfo verifyMemberInfo) {

            //导入专家库需srm内存在此用户。首先判断用户是否已存在，存在则导入数据，不存在则跳过。
            if (verifyMemberInfoService.ifHaveMemberInSrm(verifyMemberInfo.getJobnumber())) {
                //导入数据时，先删除再导入，相同工号数据会被覆盖
                verifyMemberInfoService.deleteVerifyTeamMemberInfo(verifyMemberInfo.getJobnumber());
                verifyMemberInfoService.updateVerifyMemberRole(verifyMemberInfo.getJobnumber(),"43");
                verifyMemberInfoService.importVerifyTeamMemberInfo(verifyMemberInfo);//实际导入过程，可以根据自身情况进行相应导入成功失败判断，并返回给前台
                return R.ok();
            } else {
                log.error("SRM系统中不存在此用户，请联系管理员添加！");
                return R.error(505,"SRM系统中不存在此用户，请联系管理员添加！");
            }

    }

    /**
     * 获取某个成员信息
     */
    @PostMapping("/getExpertInfo")
    @ResponseBody
    public R getExpertInfo(String jobnumber) {


        if (verifyMemberInfoService.ifHaveMemberInSrm(jobnumber)) {
            VerifyMemberInfo verifyMemberInfo = new VerifyMemberInfo();
            verifyMemberInfo.setJobnumber(jobnumber);
            return result(verifyMemberInfoService.selectVerifyMemberInfoList(verifyMemberInfo));
        } else {
            log.error("SRM系统中不存在此用户，请联系管理员添加！");
            return R.error(505,"SRM系统中不存在此用户，请联系管理员添加！");
        }

    }


//    /**
//     * 复制专家组
//     * 2020/11/29 需要传入verifytype factorycode year  starttime endtime newyear newfactorycodes newmemberids
//     */
//    @PostMapping("copyVerifyTeam")
//    @Transactional(rollbackFor = Exception.class)
//    public R copyVerifyTeam(@RequestBody Map<String,Object> copyVerifyTeamInfo)
//    {
//        try {
//            Object newfactorycodes = copyVerifyTeamInfo.get("newfactorycodes");
//            Object newmemberids = copyVerifyTeamInfo.get("newmemberids");
//            List<Object> factorycodeobjectlist = JSON.parseObject(JSON.toJSONString(newfactorycodes), List.class);
//            List<String> factorycodelist = factorycodeobjectlist.stream().map(fc -> JSON.parseObject(JSON.toJSONString(fc), String.class)).collect(Collectors.toList());
//            List<Object> memberidobjectlist = JSON.parseObject(JSON.toJSONString(newmemberids), List.class);
//            List<String> memberidlist = memberidobjectlist.stream().map(mi -> JSON.parseObject(JSON.toJSONString(mi), String.class)).collect(Collectors.toList());
//
//            createMemberTeam()
//            verifyMemberInfo.setFactorycode(verifyMemberInfo.getFactorycodes()[0]);
//            verifyMemberInfoService.copyVerifyTeam(verifyMemberInfo);
//        } catch (Exception e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return R.error("未知的错误，请检查版本号是否重复，若不重复请联系管理员");
//        }
//        return R.ok();
//    }
}
